<template>
  <div class="app-container">
    <el-tabs v-model="activeName" @tab-click="handleClick">
      <el-tab-pane label="地图模式" name="first">
        <div>
          <div class="areaSelect">
            <el-row>
              <span>{{ $t("area.Layer") }}</span>
              <treeselect
                v-model="mapValue"
                :placeholder="$t('area.chosenLayer')"
                :max-height="300"
                :options="mapList"
                @input="handleMapChange"
              />
            </el-row>
            <el-row>
              <el-button
                type="primary"
                style="position: absolute; right: 0; top: 8px"
                icon="el-icon-circle-plus-outline"
                @click="addDept()"
              >
                {{ $t('common.caddkey') }}
              </el-button>
            </el-row>
          </div>

          <!--//<el-button class="addAlarm" type="primary" disabled="true">添加告警设置</el-button>-->
          <div id="mapbox">
            <!-- 地图容器 -->
            <div
              id="map"
              :style="{ height: mapHeight, width: mapWidth }"
              style="margin-top: 10px"
            />
            <div class="isInfoShow">
              <div v-show="show4" class="fenceTable">
                <el-table
                  :data="fenceList"
                  :header-cell-style="tableHeaderColor"
                  style="width: 100%"
                >
                  <!--多选框-->
                  <!--<el-table-column prop="order" label="序号" width="50"></el-table-column>-->
                  <el-table-column
                    prop="fenceName"
                    :label="$t('area.DepartmentArea')"
                    width="150"
                  />
                  <!--操作-->
                  <el-table-column :label="$t('operating.operating')">
                    <template slot-scope="scope">
                      <el-button
                        size="mini"
                        type="danger"
                        @click="handleOneDelete(scope.$index, scope.row)"
                      >{{ $t("operating.delete") }}</el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
              <div v-show="show5" class="deptTable">
                <el-table
                  :data="deptTable"
                  :header-cell-style="tableHeaderColor"
                  style="width: 100%"
                >
                  <el-table-column
                    prop="name"
                    :label="$t('department.bindDepart')"
                  />
                </el-table>
              </div>
            </div>
            <div class="positiondiv"><span /></div>
            <div class="scalediv"><span /></div>
          </div>
        </div>
      </el-tab-pane>
      <el-tab-pane label="表格模式" name="second">
        <el-table :data="tableData" border style="width: 100%">
          <!--多选框-->
          <!--<el-table-column type="selection" width="50" align="center"></el-table-column>-->
          <el-table-column
            prop="name"
            :label="$t('department.departmentName')"
            width="180"
          />
          <el-table-column
            prop="fenceList"
            :label="$t('department.fenceList')"
            :formatter="fenceListSave"
            width="300"
          />
          <el-table-column
            prop="color"
            :label="$t('department.color')"
            width="180"
          >
            <template slot-scope="scope">
              <span
                class="typeColor"
                :style="{ background: scope.row.color }"
              />
            </template>
          </el-table-column>
          <!--操作-->
          <el-table-column :label="$t('operating.operating')">
            <template slot-scope="scope">
              <el-tooltip
                class="item"
                effect="dark"
                :content="$t('department.Untied')"
                placement="bottom"
              >
                <el-button
                  size="mini"
                  type="text"
                  icon="al-icon-carjiebang1"
                  :disabled="scope.row.fenceList.length == 0 ? true : false"
                  @click="handleDelete(scope.$index, scope.row)"
                />
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
    </el-tabs>

    <!--新增和编辑-->
    <el-dialog
      :title="$t('operating.add')"
      :close-on-click-modal="false"
      :visible.sync="editVisible"
      width="30%"
      @close="closeDialog"
    >
      <el-form ref="formDept" label-width="120px">
        <!--父级分类名称parentClassify-->
        <el-form-item :label="$t('department.departmentName')">
          <el-select
            v-model="deptValue"
            filterable
            :placeholder="$t('operating.pleaseChosen')"
            style="max-width: 215px"
          >
            <el-option
              v-for="item in deptList"
              :key="item.id"
              :label="item.label"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <!--部门颜色-->
        <el-form-item :label="$t('department.color')">
          <div class="block">
            <el-color-picker v-model="color" />
          </div>
        </el-form-item>
      </el-form>
      <!--操作-->
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="saveEdit">{{
          $t("operating.determine")
        }}</el-button>
        <el-button @click="closeDialog">{{ $t("operating.cancel") }}</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import ol from 'openlayers'
import {
  Load_Map,
  Load_Fence,
  _TransPixel,
  TagStyle,
  _dPR,
  _iMap,
  t,
  FenceLayer,
  FenceSource,
  releaseFence,
  LoadTypeData,
  sendThis
} from '@/utils/iMap.js'
import { getMapTree, getMap, checkDept, addDept, delDept, getDeptTree, deptList } from '@/api/cy.js'
import { Select } from 'ol/interaction.js'
import { baseUrl } from '@/utils/global.js'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import Cookie from 'js-cookie'

export default {
  components: { Treeselect },
  data() {
    return {
      activeName: 'first',
      tableDataUrl: '',
      deptValue: '',
      color: null, // ColorPicker 颜色选择器,无默认值；
      oldMapId: '',
      tableData: [],
      mapList: [],
      deptList: [],
      fenceList: [],
      fenceId: [],
      deptTable: [],
      mapValue: null, // 选择的地图
      text: this.$t('operating.tabularMode'),
      show: '1', // 切换显示的页面
      show3: false,
      show4: false,
      show5: false,
      mapHeight: window.innerHeight - 300 + 'px', // 地图区域高度
      mapWidth: window.innerWidth + 'px',

      /** *******************表格相关*********************/
      editVisible: false, // 编辑框是否可见
      delVisible: false, // 删除框是否可见
      _select: null,
      editEnable: true, // 点击的编辑or添加
      // 用户表单提交
      form: { dept: '' },
      selectPointerMove: null
    }
  }, // 注册树形穿梭框组件
  mounted() {
    // 动态设置map的高度
    // 首先在DOM渲染数据时，设置map的高度
    this.windowRefresh()
    // 然后监听window的resize事件，在浏览器窗口变化时再设置下map的高度
    // console.log("onresize:");
    const self = this
    window.onresize = function temp() {
      self.windowRefresh()
    }

    this.init()
  },
  methods: {
    handleClick(tab, event) {
      console.log(tab, event)
    },
    // 刷新窗口
    windowRefresh: function() {
      this.mapHeight = window.innerHeight - 300 + 'px'
      this.mapWidth = window.innerWidth + 'px'
    },
    // 修改table header的背景色
    tableHeaderColor({ row, column, rowIndex, columnIndex }) {
      if (rowIndex === 0) {
        return 'background-image:linear-gradient(to bottom , #1f59ad, #3488de);color:#fff;'
      }
    },
    // 页面显示模式
    isShowStyle() {
      if (this.show == 1) {
        // console.log(this.text);
        this.text = this.$t('operating.mapMode')
        this.show = 2
      } else if (this.show == 2) {
        this.text = this.$t('operating.tabularMode')
        this.show = 1
      }
    },
    // 重置表格显示格式
    // 所有围栏列表
    fenceListSave(row, column) {
      const fenceArr = []
      if (row.fenceList) {
        for (let j = 0; j < row.fenceList.length; j++) {
          fenceArr.push(row.fenceList[j].fenceName)
        }
        return fenceArr.join('，')
      }
    },
    // 初始化默认地图
    initMap() {
      Load_Map(
        'https://scpic.chinaz.net/files/pic/pic9/202105/apic32901.jpg',
        67.65,
        54.16,
        1600,
        1280,
        1600 / 67.65,
        [-60, -30]
      )
      sendThis(this)
      LoadTypeData()
    },
    // 初始化函数
    init: function() {
      // 加载地图树
      getMapTree().then((res) => {
        const RES = this.responseUse(res)
        this.mapList = RES
      })
      // 初始化地图
      this.initMap()

      this.getData()
      this.getDeptTree()
    },

    // 切换图层
    handleMapChange() {
      this.selectPointerMove = null
      // console.log(this.selectNew.selected.length)
      _iMap.removeInteraction(this.selectPointerMove)
      // this.v_MyMessage("选择的树分支ID：" + this.mapValue, "success");
      if (this.mapValue == '') {
        this.v_MyMessage(this.$t('Notice.mapIDIsEmpty'), 'error')
        return false
      } else {
        if (this.oldMapId != this.mapValue) {
          getMap(parseInt(this.mapValue))
            .then((res) => {
              const RES = this.responseUse(res)
              this.mapName = RES.mapName
              Load_Map(
                baseUrl + RES.mapPath,
                RES.mapActualX,
                RES.mapActualY,
                RES.mapPixelX,
                RES.mapPixelY,
                RES.mapPixelX / RES.mapActualX,
                [RES.mapOriginX, RES.mapOriginY]
              )
              this.Geo =
                baseUrl +
                '/fenceInfo/findListByFenceTypeGeoJson?fenceType=operation&layerId=' +
                this.mapValue
              releaseFence()
              Load_Fence(this.Geo)
              this.fenceSelect()
            })
        }
      }
    },
    closeDialog() {
      // this.selectPointerMove =  null;
      // console.log(this.selectNew.selected.length)
      _iMap.removeInteraction(this.selectPointerMove)
      this.editVisible = false
      this.fenceSelect()
    },
    //  选择围栏
    fenceSelect() {
      const self = this
      self.selectPointerMove = new Select()
      _iMap.addInteraction(self.selectPointerMove)
      self.selectPointerMove.on('select', function(e) {
        self.selectNew = e
        if (e.selected.length > 0) {
          // 鼠标移入，选择了一个，大概是mouseover事件
          e.selected.forEach(function(f) {
            checkDept({ fenceId: f.get('id') })
              .then((res) => {
                const RES = self.responseUse(res, true)
                if (RES) {
                  if (res.data.length > 0) {
                    self.deptTable = res.data
                    self.show5 = true
                  } else {
                    self.show5 = false
                  }
                }
              })
            let result = true
            self.fenceList.forEach((item) => {
              if (item.fenceId == f.get('id')) {
                result = false
              }
            })
            if (result) {
              self.fenceList.push({
                fenceId: f.get('id'),
                fenceName: f.get('name')
              })
            } else {
              self.v_MyMessage(this.$t('Notice.fenceAlreadyExists'), 'warning')
            }
          })
          if (self.fenceList.length > 0) {
            self.show3 = true
            self.show4 = true
          } else {
            self.show3 = false
            self.show4 = false
          }
        }
      })
    },
    // 添加部门区域信息
    addDept() {
      if (this.fenceList.length > 0) {
        this.editVisible = true
        this.editEnable = true
        this.fenceForm = {}
      } else {
        this.v_MyMessage(this.$t('Notice.fenceAreaNotSelected'), 'success')
      }
    },
    //  确认添加部门区域信息
    saveEdit: function() {
      const datas = []
      for (let i = 0; i < this.fenceList.length; i++) {
        datas.push({
          fenceId: this.fenceList[i].fenceId
        })
      }
      const param = {
        idx: this.deptValue,
        fenceList: datas,
        color: this.color
      }
      addDept(param).then((res) => {
        const RES = this.responseUse(res, true)
        if (RES) {
          this.editVisible = false
          this.fenceList = []
          this.getData()
          this.show3 = false
          this.show4 = false
        }
      })
    },
    handleDelete(index, row) {
      delDept(row.idx).then((res) => {
        const RES = this.responseUse(res, true)
        if (RES) {
          this.getData()
        }
      })
    },
    handleOneDelete(index, row) {
      this.selectIndex = index
      this.fenceList.splice(this.selectIndex, 1)
    },
    getData() {
      deptList().then((res) => {
        const RES = this.responseUse(res)
        this.tableData = RES
      })
    },
    // 获取部门列表数据
    getDeptTree() {
      getDeptTree().then((res) => {
        const RES = this.responseUse(res)
        this.deptListData(RES)
      })
    },
    deptListData(obj) {
      if (obj.length > 0) {
        for (var i = 0; i < obj.length; i++) {
          if (obj[i].children) {
            this.deptListData(obj[i].children)
          }
          this.deptList.push(obj[i])
        }
      }
    }
  }
}
</script>

<style scoped>
.areaSelect {
  position: absolute;
  right: 17px;
  width: 310px;
  margin-top: 0;
  z-index: 2000;
}
</style>
